<?php
/**
 * @version sofortueberweisung.de 5 - $Date: 2012-04-10 17:29:13 +0200 (Tue, 10 Apr 2012) $
 * @author Payment Network AG (integration@payment-network.com)
 * @link http://www.payment-network.com/
 *
 * @copyright 2006 - 2007 Henri Schmidhuber
 * @link http://www.in-solution.de
 *
 * @link http://www.xt-commerce.com
 * @license http://opensource.org/licenses/gpl-license.php GNU Public License
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; version 2 of the License
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
 * USA
 *
 ***********************************************************************************
 * this file contains code based on:
 * (c) 2000 - 2001 The Exchange Project
 * (c) 2001 - 2003 osCommerce, Open Source E-Commerce Solutions
 * (c) 2003	 nextcommerce (account_history_info.php,v 1.17 2003/08/17); www.nextcommerce.org
 * (c) 2003 - 2006 XT-Commerce
 * Released under the GNU General Public License
 ***********************************************************************************
 *
 * $Id: sofort_sofortvorkasse.php 3761 2012-04-10 15:29:13Z rotsch $
 *
 */
define('API_SV_VERSION', 'pn_xtc_5.1.0');

require_once(DIR_FS_CATALOG.'callback/sofort/sofort.php');
require_once(DIR_FS_CATALOG.'callback/sofort/library/sofortLib.php');

class sofort_sofortvorkasse extends sofort{

	var $code, $title, $description, $enabled, $sofort, $paymentMethod;

	function sofort_sofortvorkasse() {
		global $order;

		$this->checkExistingSofortConstants('sv');

		$this->code = 'sofort_sofortvorkasse';
		$this->title = MODULE_PAYMENT_SOFORT_SV_TEXT_TITLE ;
		$this->title_extern = MODULE_PAYMENT_SOFORT_SOFORTVORKASSE_TEXT_TITLE;
		$this->paymentMethod = 'SV';

		if(MODULE_PAYMENT_SOFORT_SV_KS_STATUS == 'True'){
			$this->title_extern = MODULE_PAYMENT_SOFORT_SV_KS_TEXT_TITLE;
		}

		if (MODULE_PAYMENT_SOFORT_SV_RECOMMENDED_PAYMENT == 'True') {
			$this->title_extern .= ' ' . MODULE_PAYMENT_SOFORT_SV_RECOMMENDED_PAYMENT_TEXT;
		}

		$this->description = MODULE_PAYMENT_SOFORT_SV_TEXT_DESCRIPTION;
		$this->sort_order = MODULE_PAYMENT_SOFORT_SV_SORT_ORDER;
		$this->enabled = ((MODULE_PAYMENT_SOFORT_SV_STATUS == 'True') ? true : false);
		$this->tmpOrders = true;
		$this->tmpStatus = MODULE_PAYMENT_SOFORT_SV_TMP_STATUS_ID;
		if (is_object($order)) {
			$this->update_status();
		}
		$this->defaultCurrency = DEFAULT_CURRENCY;
		$this->sofort = new SofortLib_Multipay(MODULE_PAYMENT_SOFORT_MULTIPAY_APIKEY);

		$this->sofort->setVersion(API_SV_VERSION);

		$this->form_action_url = "";
	}


	function selection () {

		$title = '';

		switch (MODULE_PAYMENT_SOFORT_MULTIPAY_IMAGE) {
			case 'Logo & Text':
				if(MODULE_PAYMENT_SOFORT_SV_KS_STATUS == 'True') {
					$title = $this->setImageText('logo_155x50.png', MODULE_PAYMENT_SOFORT_MULTIPAY_SV_CHECKOUT_TEXT);
				} else {
					$title = $this->setImageText('logo_155x50.png', MODULE_PAYMENT_SOFORT_MULTIPAY_SV_CHECKOUT_TEXT);
				}
				break;
			case 'Infographic':
				if(MODULE_PAYMENT_SOFORT_SV_KS_STATUS == 'True') {
					$title = $this->setImageText('banner_400x100_ks.png', '');
				} else {
					$title = $this->setImageText('banner_300x100.png', '');
				}
				break;
		}

		$cost = '';
		if(array_key_exists('ot_sofort',  $GLOBALS)) {
			$cost = $GLOBALS['ot_sofort']->get_percent($this->code, 'price');
		}

		$conditionsChecked = false;
		if($_SESSION['sofort_conditions_sv'] == 'sofort_conditions_sv') {
			$conditionsChecked = true;
		}

		$fields = array(
				array('title' => MODULE_PAYMENT_SOFORT_SV_CHECKOUT_CONDITIONS,
						'field' => xtc_draw_checkbox_field('sofort_conditions_sv', 'sofort_conditions_sv', $conditionsChecked))
		);

		return array('id' => $this->code , 'module' => $this->title_extern , 'fields' => $fields, 'description' => $title, 'module_cost' => $cost	);

	}

	function setImageText($image, $text) {
		switch ($_SESSION['language']){
			case 'german': $image = 'https://images.sofort.com/de/sv/'.$image; break;
			case 'dutch':  $image = 'https://images.sofort.com/nl/sv/'.$image; break;
			case 'polish': $image = 'https://images.sofort.com/pl/sv/'.$image; break;
			//english is fallback for unknown langs
			case 'english':
			default:	   $image = 'https://images.sofort.com/en/sv/'.$image; break;
		}
		$image = xtc_image($image, MODULE_PAYMENT_SOFORT_SV_TEXT_DESCRIPTION_CHECKOUT_PAYMENT_IMAGEALT);
		$title = MODULE_PAYMENT_SOFORT_SV_TEXT_DESCRIPTION_CHECKOUT_PAYMENT_IMAGE;
		$title = str_replace('{{image}}', $image, $title);
		$title = str_replace('{{text}}', $text, $title);
		return $title;
	}

	function pre_confirmation_check ($vars = '') {

		parent::pre_confirmation_check ($vars);

		//in CommerceSEO check is done with Ajax
		if (isset ($_POST['xajax']) && $_POST['xajax'] == 'updatePaymentModule' ) {
			$data_arr = $vars;
			if (!$data_arr['sofort_conditions_sv'] == 'sofort_conditions_sv') {
				unset($_SESSION['sofort_conditions_sv']);
			}
			$is_ajax = true;
		} else {
			array_walk($_POST, 'maskSpecialChars');
			$data_arr = $_POST;
		}

		if ($data_arr['sofort_conditions_sv']) {
			$_SESSION['sofort_conditions_sv'] = $data_arr['sofort_conditions_sv'];
		}

		if ($data_arr['sofort_conditions_sv'] != 'sofort_conditions_sv' && $_SESSION['sofort_conditions_sv'] != 'sofort_conditions_sv') {
			if ($is_ajax) {
				$payment_error_return = 'payment_error='.$this->code.'&error='.urlencode(MODULE_PAYMENT_SOFORT_MULTIPAY_XML_FAULT_10002);
				$_SESSION['checkout_payment_error'] = $payment_error_return;
			} else {
				$payment_error_return = 'payment_error='.$this->code.'&error_codes=10002';
				xtc_redirect(xtc_href_link(FILENAME_CHECKOUT_PAYMENT, $payment_error_return, 'SSL', true, false));
			}
		}

		return false;
	}


	function after_process() {
		global $insert_id;

		if ($_GET['all_inserted']) {
			return false;
		}

		//delete sofort-vars in the session and set customer notified if user got an order-email
		parent::after_process();

		//save sofortvorkasse-bankdata in customer history and show bankdata-page
		$bankdata = //MODULE_PAYMENT_SOFORT_SV_CHECKOUT_HEADING_TEXT.': '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_HOLDER_TEXT.' '.helperFunctions::htmlMask($_GET['holder']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_ACCOUNT_NUMBER_TEXT.' '.helperFunctions::htmlMask($_GET['account_number']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_IBAN_TEXT.' '.helperFunctions::htmlMask($_GET['iban']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_BANK_CODE_TEXT.' '.helperFunctions::htmlMask($_GET['bank_code']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_BIC_TEXT.' '.helperFunctions::htmlMask($_GET['bic']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_AMOUNT_TEXT.' '.helperFunctions::htmlMask($_GET['amount']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_REASON_1_TEXT.' '.helperFunctions::htmlMask($_GET['reason_1']).' -- '.
			MODULE_PAYMENT_SOFORT_SV_CHECKOUT_REASON_2_TEXT.' '.helperFunctions::htmlMask($_GET['reason_2']);

		$tmpStatusId = $this->checkStatusId(MODULE_PAYMENT_SOFORT_SV_TMP_STATUS_ID);

		$sql_data_array = array('orders_id' => $insert_id,
				'orders_status_id' => (int) $tmpStatusId,
				'date_added' => 'sqlcommand:now()',
				'customer_notified' => HelperFunctions::getIniValue('sofortCustomerNotified'), //(SEND_EMAILS == 'true') ? '1' : '0',
				'comments' => $bankdata);
		xtc_db_query(helperFunctions::getEscapedInsertInto(TABLE_ORDERS_STATUS_HISTORY, $sql_data_array));

		//@see checkout_process.php
		$_SESSION['cart']->reset(true);
		// unregister session variables used during checkout
		if (isset($_SESSION['sendto'])) 		unset ($_SESSION['sendto']);
		if (isset($_SESSION['billto'])) 		unset ($_SESSION['billto']);
		if (isset($_SESSION['shipping'])) 		unset ($_SESSION['shipping']);
		if (isset($_SESSION['payment'])) 		unset ($_SESSION['payment']);
		if (isset($_SESSION['comments'])) 		unset ($_SESSION['comments']);
		if (isset($_SESSION['last_order']))		unset ($_SESSION['last_order']);
		if (isset($_SESSION['tmp_oID'])) 		unset ($_SESSION['tmp_oID']);
		if (isset($_SESSION['cc'])) 			unset ($_SESSION['cc']);
		if (isset ($_SESSION['credit_covers']))	unset ($_SESSION['credit_covers']);
		
		global $order_total_modules;
		if (is_object($order_total_modules)) {
			$order_total_modules->clear_posts();
		}
		
		//show bankdata to buyer when paying with vorkasse
		if (ENABLE_SSL == true)
			$server = HTTPS_SERVER;
		else
			$server = HTTP_SERVER;
		$session = '&' . session_name() . '=' . session_id();
		$get = '&holder='.helperFunctions::htmlMask($_GET['holder']).'&account_number='.helperFunctions::htmlMask($_GET['account_number']).'&iban='.helperFunctions::htmlMask($_GET['iban']).'&bank_code='.helperFunctions::htmlMask($_GET['bank_code']).'&bic='.helperFunctions::htmlMask($_GET['bic']).'&amount='.helperFunctions::htmlMask($_GET['amount']).'&reason_1='.helperFunctions::htmlMask($_GET['reason_1']).'&reason_2='.helperFunctions::htmlMask($_GET['reason_2']);
		xtc_redirect($server . DIR_WS_CATALOG . 'callback/sofort/confirmVorkasse.php?'.$get.$session);
	}


	function install() {
		$sofortStatuses = $this->insertAndReturnSofortStatus();
		$tempStatus = 		(isset($sofortStatuses['temp']) 	&& !empty($sofortStatuses['temp']))		? $sofortStatuses['temp'] : '';
		$confirmedStatus = 	(isset($sofortStatuses['confirmed'])&& !empty($sofortStatuses['confirmed']))? $sofortStatuses['confirmed'] : '';

		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_STATUS', 'True', '6', '1', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_KS_STATUS', 'False', '6', '100', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_SOFORT_SV_SORT_ORDER', '0', '6', '20', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_ORDER_STATUS_ID', '".helperFunctions::escapeSql($confirmedStatus)."',  '6', '10', 'xtc_cfg_pull_down_order_statuses(', 'xtc_get_order_status_name', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, use_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_TMP_STATUS_ID', '".helperFunctions::escapeSql($tempStatus)."',  '6', '8', 'xtc_cfg_pull_down_order_statuses(', 'xtc_get_order_status_name', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, set_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_RECOMMENDED_PAYMENT', 'False', '6', '1', 'xtc_cfg_select_option(array(\'True\', \'False\'), ', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, date_added) values ('MODULE_PAYMENT_SOFORT_SOFORTVORKASSE_ALLOWED', '', '6', '0', now())");
		xtc_db_query("INSERT INTO " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " ( configuration_key, configuration_value,  configuration_group_id, sort_order, use_function, set_function, date_added) values ('MODULE_PAYMENT_SOFORT_SV_ZONE', '0', '6', '2', 'xtc_get_zone_class_title', 'xtc_cfg_pull_down_zone_classes(', now())");

		//install shared keys, that are used by all/most multipay-modules
		parent::install();
	}


	function remove() {
		xtc_db_query("delete from " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " where configuration_key LIKE 'MODULE_PAYMENT_SOFORT_SV%'");
		xtc_db_query("delete from " . helperFunctions::escapeSql(TABLE_CONFIGURATION) . " where configuration_key LIKE 'MODULE_PAYMENT_SOFORT_SOFORTVORKASSE%'");

		//if this is the last removing of a multipay-paymentmethod --> we also remove all shared keys, that are used by all/most multipay-modules
		parent::remove();
	}


	function keys() {
		return array('MODULE_PAYMENT_SOFORT_SV_STATUS',
				'MODULE_PAYMENT_SOFORT_MULTIPAY_APIKEY',
				'MODULE_PAYMENT_SOFORT_MULTIPAY_AUTH',
				'MODULE_PAYMENT_SOFORT_SV_RECOMMENDED_PAYMENT',
				//'MODULE_PAYMENT_SOFORT_SV_KS_STATUS',
				'MODULE_PAYMENT_SOFORT_SOFORTVORKASSE_ALLOWED' ,
				'MODULE_PAYMENT_SOFORT_SV_ZONE' ,
				'MODULE_PAYMENT_SOFORT_MULTIPAY_REASON_1',
				//'MODULE_PAYMENT_SOFORT_MULTIPAY_IMAGE',
				'MODULE_PAYMENT_SOFORT_SV_TMP_STATUS_ID',
				'MODULE_PAYMENT_SOFORT_SV_ORDER_STATUS_ID',
				'MODULE_PAYMENT_SOFORT_MULTIPAY_CANCELED_ORDER_STATUS_ID',
				'MODULE_PAYMENT_SOFORT_SV_SORT_ORDER');
	}
}
?>